public class Solution543 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max=0;

    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);
        return max-1;
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int x=dfs(root.left);
        int y=dfs(root.right);
        max=Math.max(max,x+y+1);
        return Math.max(x,y)+1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution543().diameterOfBinaryTree(new TreeNode(1,new TreeNode(2,new TreeNode(3),new TreeNode(4)),new TreeNode(5))));
    }
}
